"""
评估相关的 Pydantic 模型
"""
from typing import Optional, Any
from datetime import datetime
from uuid import UUID
from pydantic import BaseModel, Field, ConfigDict, field_validator
from enum import Enum


# ========== 枚举类型 ==========
class EvaluationMode(str, Enum):
    """评估模式"""
    RULE_BASED = "rule-based"  # 基于规则
    AI_BASED = "ai-based"  # 基于AI
    HYBRID = "hybrid"  # 混合模式


class IssueType(str, Enum):
    """问题类型"""
    COMPLETENESS = "completeness"  # 完整性
    STANDARDIZATION = "standardization"  # 规范性
    CONSISTENCY = "consistency"  # 一致性
    ACCURACY = "accuracy"  # 准确性


class IssueSeverity(str, Enum):
    """问题严重程度"""
    CRITICAL = "critical"  # 严重
    MAJOR = "major"  # 主要
    MINOR = "minor"  # 次要
    INFO = "info"  # 提示


class AssessmentStatus(str, Enum):
    """评估状态"""
    PENDING = "pending"  # 待评估
    PROCESSING = "processing"  # 评估中
    COMPLETED = "completed"  # 已完成
    FAILED = "failed"  # 失败


# ========== 问题详情 ==========
class AssessmentIssueBase(BaseModel):
    """问题基础模型"""
    issue_type: IssueType = Field(description="问题类型")
    severity: IssueSeverity = Field(description="严重程度")
    field_name: Optional[str] = Field(default=None, description="问题字段名")
    issue_description: str = Field(description="问题描述")
    suggestion: Optional[str] = Field(default=None, description="改进建议")
    score_deduction: int = Field(default=0, ge=0, description="扣分")


class AssessmentIssueCreate(AssessmentIssueBase):
    """创建问题"""
    pass


class AssessmentIssueResponse(AssessmentIssueBase):
    """问题响应"""
    id: UUID
    assessment_id: UUID
    created_at: datetime
    
    model_config = ConfigDict(from_attributes=True)


# ========== 评估结果 ==========
class DimensionScores(BaseModel):
    """各维度评分"""
    completeness: int = Field(ge=0, le=100, description="完整性评分")
    standardization: int = Field(ge=0, le=100, description="规范性评分")
    consistency: int = Field(ge=0, le=100, description="一致性评分")
    accuracy: int = Field(ge=0, le=100, description="准确性评分")


class DimensionWeights(BaseModel):
    """维度权重"""
    completeness: float = Field(default=0.30, ge=0, le=1, description="完整性权重")
    standardization: float = Field(default=0.25, ge=0, le=1, description="规范性权重")
    consistency: float = Field(default=0.25, ge=0, le=1, description="一致性权重")
    accuracy: float = Field(default=0.20, ge=0, le=1, description="准确性权重")
    
    @field_validator('completeness', 'standardization', 'consistency', 'accuracy')
    @classmethod
    def validate_weight(cls, v: float) -> float:
        """验证权重范围"""
        if not 0 <= v <= 1:
            raise ValueError("权重必须在 0-1 之间")
        return v


class AssessmentBase(BaseModel):
    """评估基础模型"""
    evaluation_mode: EvaluationMode = Field(description="评估模式")
    overall_score: int = Field(ge=0, le=100, description="综合评分")
    completeness_score: int = Field(ge=0, le=100, description="完整性评分")
    standardization_score: int = Field(ge=0, le=100, description="规范性评分")
    consistency_score: int = Field(ge=0, le=100, description="一致性评分")
    accuracy_score: int = Field(ge=0, le=100, description="准确性评分")
    summary: Optional[str] = Field(default=None, description="评估总结")
    suggestions: Optional[list[str]] = Field(default=None, description="改进建议")


class AssessmentCreate(BaseModel):
    """创建评估请求"""
    record_id: UUID = Field(description="病历ID")
    evaluation_mode: EvaluationMode = Field(
        default=EvaluationMode.RULE_BASED,
        description="评估模式"
    )
    weights: Optional[DimensionWeights] = Field(
        default=None,
        description="自定义权重（不提供则使用默认值）"
    )


class AssessmentResponse(AssessmentBase):
    """评估响应"""
    id: UUID
    record_id: UUID
    assessed_at: datetime
    assessment_duration: Optional[int] = Field(default=None, description="评估耗时(ms)")
    status: AssessmentStatus
    
    model_config = ConfigDict(from_attributes=True)


class AssessmentDetailResponse(AssessmentResponse):
    """评估详细响应（包含问题列表）"""
    issues: list[AssessmentIssueResponse] = Field(default_factory=list)


# ========== 评估报告 ==========
class AssessmentReport(BaseModel):
    """完整评估报告"""
    assessment: AssessmentDetailResponse
    record: dict[str, Any] = Field(description="病历基本信息")
    statistics: dict[str, Any] = Field(description="统计信息")
    charts_data: dict[str, Any] = Field(description="图表数据")


class AssessmentStatistics(BaseModel):
    """评估统计"""
    total_records: int = Field(description="病历总数")
    assessed_records: int = Field(description="已评估数量")
    average_score: float = Field(description="平均分")
    score_distribution: dict[str, int] = Field(description="分数分布")
    common_issues: list[dict[str, Any]] = Field(description="常见问题")


# ========== 批量评估 ==========
class BatchAssessmentRequest(BaseModel):
    """批量评估请求"""
    record_ids: list[UUID] = Field(description="病历ID列表")
    evaluation_mode: EvaluationMode = Field(
        default=EvaluationMode.RULE_BASED,
        description="评估模式"
    )


class BatchAssessmentResponse(BaseModel):
    """批量评估响应"""
    total: int = Field(description="总数")
    success: int = Field(description="成功数量")
    failed: int = Field(description="失败数量")
    results: list[AssessmentResponse] = Field(description="评估结果")
    errors: list[dict[str, str]] = Field(default_factory=list, description="错误信息")

